<script setup lang="ts">
import type { Project } from '#/api/business/project/model';
import type { Menu } from '#/api/system/menu/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import {
  addFullName,
  cloneDeep,
  getPopupContainer,
  listToTree,
} from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { projectAdd, projectList, projectUpdate } from '#/api/business/project';
import { uploadApiNew } from '#/api/core/upload';
import { Tinymce } from '#/components/tinymce';
import { formatToFen, formatToYuan } from '#/utils/common';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';

interface ProjectProps extends Project {
  update: boolean;
}

interface FlattenMenu extends Omit<Menu, 'childMenuList'> {
  menuId: number;
}

const emit = defineEmits<{ reload: [] }>();
const serviceContent = ref('');
const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const projectImg = ref<string>('');
const handleUpload = (file: File) => {
  uploadApiNew({
    file,
    onSuccess: (data) => {
      console.log('data :>>', data);
      projectImg.value = data.objectName;
    },
  });
};
const handleRemove = () => {
  projectImg.value = '';
};

const projectDetailImgList = ref<string[]>([]);
const handleUploadDetail = (file: File) => {
  uploadApiNew({
    file,
    onSuccess: (data) => {
      console.log('data :>>', data);
      projectDetailImgList.value.push(data.objectName);
    },
  });
};
const handleRemoveDetail = () => {
  projectDetailImgList.value = [];
};
const parentId = ref<number>(0);
const handleTreeChange = (value: number) => {
  console.log('value :>>', value);
  parentId.value = value;
};

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  schema: drawerSchema(
    handleUpload,
    handleRemove,
    handleUploadDetail,
    handleRemoveDetail,
    handleTreeChange,
  ),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

function flattenMenu(arr: Project[]) {
  const result: FlattenMenu[] = [];

  function traverse(menu: Project) {
    // 跳过空对象
    if (Object.keys(menu).length === 0) return;

    const { childProject, id, projectName, ...rest } = menu;

    // 创建新对象，将 id 改为 menuId
    const newMenu: FlattenMenu = {
      menuId: id,
      menuName: projectName,
      id,
      ...rest,
    };

    result.push(newMenu);
  }

  // 遍历原始数组中的每个菜单项
  arr.forEach((menu: Project) => traverse(menu));

  return result;
}

async function setupMenuSelect() {
  // menu
  const data = await projectList({
    pageNo: 1,
    pageSize: 1000,
  });
  const menuArray = flattenMenu(data.records);
  // console.log('menuArray :>>', JSON.stringify(menuArray));
  // const folderArray = menuArray.filter((item) => item.menuType === 'M');
  /**
   * 这里需要过滤掉按钮类型
   * 不允许在按钮下添加数据
   */
  const menuTree = listToTree(menuArray, { id: 'menuId', pid: 'parentId' });
  const fullMenuTree = [
    {
      menuId: 0,
      menuName: $t('menu.root'),
      children: menuTree,
    },
  ];
  addFullName(fullMenuTree, 'menuName', ' / ');
  // console.log('menuTree :>>', menuTree);
  formApi.updateSchema([
    {
      componentProps: {
        fieldNames: {
          label: 'menuName',
          value: 'menuId',
        },
        getPopupContainer,
        // 设置弹窗滚动高度 默认256
        listHeight: 300,
        showSearch: true,
        treeData: fullMenuTree,
        treeDefaultExpandAll: false,
        // 默认展开的树节点
        treeDefaultExpandedKeys: [0],
        treeLine: { showLeafIcon: false },
        // 筛选的字段
        treeNodeFilterProp: 'menuName',
        treeNodeLabelProp: 'fullName',
      },
      fieldName: 'parentId',
    },
  ]);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const {
      projectImg: projectImgValue,
      projectDetailImgList: projectDetailImgListValue,
      id,
      update,
      projectPrice,
      parentId: parentIdValue,
      serviceContent: serviceContentValue,
      ...rest
    } = modalApi.getData() as ProjectProps;
    isUpdate.value = update;

    // 加载菜单树选择
    await setupMenuSelect();
    if (id) {
      // await formApi.setFieldValue('parentId', id);
      console.log('projectDetailImgListValue :>>', projectDetailImgListValue);
      parentId.value = parentIdValue;
      if (update) {
        serviceContent.value = serviceContentValue;
        const objectName = projectImgValue && projectImgValue.split('/').pop();

        const objectNameList = [];
        projectDetailImgListValue &&
          projectDetailImgListValue.forEach((item) => {
            const objectName = item.split('/').pop();
            projectDetailImgList.value.push(objectName);
            objectNameList.push({
              uid: '-1',
              name: objectName,
              status: 'done',
              url: item,
            });
          });

        projectImg.value = objectName || '';
        // console.log('objectNameList :>>', objectNameList);
        await formApi.setValues({
          ...rest,
          id,
          parentId: parentIdValue,
          projectImg: projectImgValue
            ? [
                {
                  uid: '-1',
                  name: objectName,
                  status: 'done',
                  url: projectImgValue,
                },
              ]
            : undefined,
          projectDetailImgList: objectNameList,
          projectPrice: projectPrice ? formatToYuan(projectPrice) : undefined,
        });
      }
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    data.projectImg = projectImg.value;
    data.projectDetailImgList = projectDetailImgList.value.map((item) => item);
    data.projectPrice = formatToFen(data.projectPrice);
    data.serviceContent = serviceContent.value;
    console.log('data :>>', data);
    // return;
    await (isUpdate.value ? projectUpdate(data) : projectAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  serviceContent.value = '';
  projectImg.value = '';
  projectDetailImgList.value = [];
  parentId.value = 0;
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[1200px]">
    <BasicForm />
    <div class="pl-4" v-if="parentId !== 0">
      <div class="mb-2">服务内容</div>
      <Tinymce v-model="serviceContent" :height="600" />
    </div>
  </BasicModal>
</template>
